package com.smarthome.ipc.command;

import org.springframework.stereotype.Service;

import com.smarthome.domain.ipc.IpcCodeEnum;
import com.smarthome.domain.ipc.IpcConstants;
import com.smarthome.domain.ipc.IpcResponse;
import com.smarthome.domain.ipc.req.HkIpcResidenceDoorOpRequest;
import com.smarthome.common.tools.BossCachedKeysUtil;
import com.smarthome.ipc.hk.HKMainService;
import com.smarthome.ipc.hk.demo.HCNetSDK;
import com.smarthome.ipc.hk.demo.HCNetSDK.NET_DVR_CONTROL_GATEWAY;
import com.smarthome.ipc.hk.entity.NetDvrLoginV30Entity;
import com.sun.jna.Pointer;

/**
 * 海康门口机 门禁模块指令模块-开门
 * 
 * @author add by denghw 2015/09/21
 *
 */
@Service(IpcConstants.IPC_COMMAND_RESIDENCE_DOOR_HK)
public class HkNetDvrControlGatewayOpen extends HKMainService {

	@Override
	protected void doCmd(HkIpcResidenceDoorOpRequest request, IpcResponse<?> response) {
		// TODO Auto-generated method stub
		// 1.获取唯一的操作句柄
		NetDvrLoginV30Entity clickObj = (NetDvrLoginV30Entity) localCache.get(BossCachedKeysUtil
				.getKey(BossCachedKeysUtil.MODULE_HK_TALKDOOR_DEVICE, request.getIp() + request.getDeviceId()));
		if (IpcConstants.IPC_COMMAND_RESIDENCE_DOOR_HK_OPEN.equals(request.getDoorOp())) {
			// 2.开门
			// 这里默认情况是打开门口机所有的门,要根据实际施工情况来看,有哪些门再做调整
			NET_DVR_CONTROL_GATEWAY controlgateway = new HCNetSDK.NET_DVR_CONTROL_GATEWAY();
			controlgateway.write();
			controlgateway.dwSize = controlgateway.size();
			controlgateway.byCommand = 1;
			controlgateway.dwGatewayIndex = 1;
			String src = new String("aaaaaaaa");
			byte[] srcbytes = src.getBytes();
			byte[] topbytes = new byte[HCNetSDK.NAME_LEN];
			System.arraycopy(srcbytes, 0, topbytes, 0, srcbytes.length);
			controlgateway.byControlSrc = topbytes;
			controlgateway.write();
			Pointer controlgatewaypointer = controlgateway.getPointer();
			boolean rtnflag = clickObj.gethCNetSDK().NET_DVR_RemoteControl(clickObj.getiUserId(),
					HCNetSDK.NET_DVR_REMOTECONTROL_GATEWAY, controlgatewaypointer, controlgateway.size());
			controlgateway.read();
			if (!rtnflag) {
				rtnBackErrMsg(request.getDeviceId(), request.getCommand(),
						String.valueOf(clickObj.gethCNetSDK().NET_DVR_GetLastError()), "开门失败");
				response.setIpcCodeObj(IpcCodeEnum.SYSTEM_ERROR);
				return;
			}
		} else {
			rtnBackErrMsg(request.getDeviceId(), request.getCommand(), IpcCodeEnum.COMMAND_NOT_FOUND.getCode(),
					IpcCodeEnum.COMMAND_NOT_FOUND.getMsg());
			response.setIpcCodeObj(IpcCodeEnum.COMMAND_NOT_FOUND);
			return;
		}
		// 3.成功
		response.setIpcCodeObj(IpcCodeEnum.SYSTEM_SUCCESS);
	}

}
